package gitlabapi

import (
	"encoding/json"
	"fmt"
	"github.com/sirupsen/logrus"
	"gitlab-sync/config"
	"gitlab-sync/util"
)

type Members struct {
	Id           int    `json:"id"`
	Name         string `json:"name"`
	Username     string `json:"username"`
	Access_level int    `json:"access_level"`
}

type MemberShip struct {
	User_id      int `json:"user_id"`
	Access_level int `json:"access_level"`
}

func CreateMembers(odlId int, newId int, isGroup bool) {
	if isGroup {
		logrus.Print("开始同步group member")
	} else {
		logrus.Print("开始同步project member")
	}

	oldurl := ""
	newurl := ""
	if isGroup {
		oldurl = fmt.Sprintf(config.GetConfig().Gitlab.OriginRemoteUrl+config.GetConfig().Gitlab.GroupsApi+"/%d/members", odlId)
		newurl = fmt.Sprintf(config.GetConfig().Gitlab.TargetRemoteUrl+config.GetConfig().Gitlab.GroupsApi+"/%d/members", newId)
	} else {
		oldurl = fmt.Sprintf(config.GetConfig().Gitlab.OriginRemoteUrl+config.GetConfig().Gitlab.ProjectsApi+"/%d/members", odlId)
		newurl = fmt.Sprintf(config.GetConfig().Gitlab.TargetRemoteUrl+config.GetConfig().Gitlab.ProjectsApi+"/%d/members", newId)
	}
	members := getMembers(oldurl)
	if members == nil {
		return
	}
	members2 := getNewMembers(members, fmt.Sprintf(config.GetConfig().Gitlab.TargetRemoteUrl+config.GetConfig().Gitlab.UsersApi))
	logrus.Print("开始同步成员")
	if members2 == nil {
		logrus.Print("无成员，不需要同步")
	}
	for _, members := range members2 {
		createMemberShip(newurl, members)
	}
	if isGroup {
		logrus.Print("同步group member结束")
	} else {
		logrus.Print("同步project member结束")
	}
}

// 获取用户
func getMembers(url string) []Members {
	logrus.Print("获取旧仓库绑定的成员")
	body := util.Get2(url, config.GetConfig().OriginGitlab.PrivateToken, config.GetConfig().Log.RequestLog)
	var members []Members
	err := json.Unmarshal(body, &members)
	if err != nil {
		logrus.Error("Error:", err)
		return nil
	}
	if len(members) == 0 {
		logrus.Print("响应结果：没有绑定成员")
		return nil
	}
	return members
}

func getNewMembers(oldmenbers []Members, url string) (members []MemberShip) {
	logrus.Print("去目标仓库创建用户")
	var result []MemberShip
	if oldmenbers != nil {
		for _, oldmenbers := range oldmenbers {
			search_url := url + "?private_token=" + config.GetConfig().TargetGitlab.PrivateToken + "&username=" + oldmenbers.Username
			body := util.Get(search_url, config.GetConfig().Log.RequestLog)
			var user []Users
			err := json.Unmarshal(body, &user)
			if err != nil || len(user) == 0 {
				logrus.Printf("[%s]用户不存在\n", oldmenbers.Username)
				user = CreateUsers(oldmenbers.Username)
			} else {
				member := MemberShip{User_id: user[0].Id, Access_level: oldmenbers.Access_level}
				result = append(result, member)
			}
		}
	}
	logrus.Print("目标仓库创建用户完成")
	return result
}

// 创建用户
func createMemberShip(api string, members MemberShip) {
	logrus.Printf("userid[%d]", members.User_id)
	url := fmt.Sprintf(api)
	bytesData, _ := json.Marshal(members)
	util.Post(url, bytesData, config.GetConfig().TargetGitlab.PrivateToken, config.GetConfig().Log.RequestLog)
}
